package cn.com.zero.front.auth.controller;

import cn.com.zero.api.message.dubbo.IMessageService;
import cn.com.zero.base.constant.ZeroRegexPatternConstants;
import cn.com.zero.base.exception.ErrorCodeException;
import cn.com.zero.base.vo.ResponseVO;
import cn.com.zero.common.auth.security.po.AuthUserPO;
import cn.com.zero.common.auth.util.AuthUtil;
import cn.com.zero.front.auth.constant.FrontAuthConstants;
import cn.com.zero.front.auth.po.AuthUserInfoPO;
import cn.com.zero.front.auth.service.IUserService;
import cn.com.zero.web.controller.BaseController;
import cn.com.zero.web.util.HttpRequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Pattern;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 用户controller
 * @createTime 2023/3/30 16:24
 */
@Validated
@RestController
@Api(tags = "用户接口")
@RequestMapping("/front/auth/user")
public class UserController extends BaseController {

    private IMessageService messageService;
    private IUserService userService;


    @ApiOperation("查询个人信息")
    @GetMapping("/info")
    public AuthUserInfoPO getAuthUserInfoPO() {
        String userId = AuthUtil.getUserIdFromRequest();
        return userService.getAuthUserInfoPO(userId);
    }


    @ApiOperation("手机号登录时发送验证码")
    @ApiImplicitParam(paramType = "query", name = "mobilePhone", required = true, value = "手机号")
    @PostMapping("/login/sendVerifyCode")
    public void sendVerifyCodeL(@Pattern(regexp = ZeroRegexPatternConstants.MOBILE_EX) @RequestParam("mobilePhone") String mobilePhone) {
        try {
            // 判断手机号是否已经存在
            AuthUserPO userPO = userService.queryUserByMobilePhone(mobilePhone);
            if (userPO == null) {
                logger.debug("用户登录时，该手机号{}未注册", mobilePhone);
                return;
            }
            String requestIp = HttpRequestUtil.getRequestIp();
            messageService.sendVerificationCode(mobilePhone, FrontAuthConstants.CODE_MESSAGE_TYPE_LOGIN_VERIFICATION, requestIp);
            logger.debug("手机号登录验证码发送成功，手机号：{}", mobilePhone);

        } catch (Exception e) {
            logger.error("手机号登录发送验证码异常:{}", e.getMessage());
        }
    }


    @ApiOperation(value = "设置/修改头像，返回key值：修改成功后返回头像文件名")
    @ApiImplicitParam(paramType = "query", name = "avatar", required = true, value = "头像文件")
    @PostMapping("/updateAvatar")
    public ResponseVO updateAvatar(@RequestParam("avatar") MultipartFile avatar) {
        String userId = AuthUtil.getUserIdFromRequest();
        return ResponseVO.success(userService.updateAvatar(userId, avatar));
    }


    @ApiOperation(value = "设置/修改登录用户名")
    @ApiImplicitParam(paramType = "query", name = "userName", required = true, value = "登录用户名")
    @PostMapping("/updateUserName")
    public void updateUserName(@RequestParam(value = "userName") String userName) {
        String userId = AuthUtil.getUserIdFromRequest();
        userService.updateUserName(userId, userName);
    }


    @ApiOperation(value = "绑定手机号发送验证码")
    @ApiImplicitParam(paramType = "query", name = "mobilePhone", required = true, value = "手机号；明文")
    @PostMapping("/blindMobile/sendVerifyCode")
    public void sendVerifyCodeM(@Pattern(regexp = ZeroRegexPatternConstants.MOBILE_EX) @RequestParam("mobilePhone") String mobilePhone) {
        try {
            // 判断手机号是否已经存在
            AuthUserPO userPO = userService.queryUserByMobilePhone(mobilePhone);
            if (userPO != null) {
                logger.debug("绑定手机号时，手机号已经存在，手机号：{}", mobilePhone);
                return;
            }
            // 发注册验证码
            String requestIp = HttpRequestUtil.getRequestIp();
            messageService.sendVerificationCode(mobilePhone, FrontAuthConstants.CODE_MESSAGE_TYPE_BLIND_MOBILE, requestIp);
            logger.debug("绑定手机号验证码发送成功，手机号：{}", mobilePhone);
        } catch (Exception e) {
            logger.error("绑定手机号发送验证码异常", e);
        }
    }

    @ApiOperation(value = "设置/更改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mobilePhone", required = true, value = "手机号；明文"),
            @ApiImplicitParam(paramType = "query", name = "verifyCode", required = true, value = "手机验证码")
    })
    @PostMapping("/modifyMobile")
    public void modifyMobile(@Pattern(regexp = ZeroRegexPatternConstants.MOBILE_EX) @RequestParam("mobilePhone") String mobilePhone, @RequestParam("verifyCode") String verifyCode) {
        // 通过手机号查询用户信息
        AuthUserPO userPO = userService.queryUserByMobilePhone(mobilePhone);
        if (userPO != null) {
            // 验证新手机号是否存在
            logger.debug("绑定手机号时，手机号已经存在，手机号：{}", mobilePhone);
            throw new ErrorCodeException(-20000L);
        }

        Long res = messageService.checkVerificationCode(mobilePhone, FrontAuthConstants.CODE_MESSAGE_TYPE_BLIND_MOBILE, verifyCode);
        if (res == null || res < 0) {
            throw new ErrorCodeException(-20001L);
        }

        // 修改客户的新手机号
        String userId = AuthUtil.getUserIdFromRequest();
        userService.modifyMobile(userId, mobilePhone);
    }


    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @DubboReference
    public void setMessageService(IMessageService messageService) {
        this.messageService = messageService;
    }
}
